#include <cserver/restapi.h>
#include <boost/log/trivial.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/common/listuser";

	void list_user(Request& req, pqxx::connection&, SessionContext& sctx, const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto& from_s = query["from"];
		auto& count_s = query["count"];
		size_t from = from_s.empty() ? size_t(0): boost::lexical_cast<unsigned>(from_s);
		size_t limit = count_s.empty() ? size_t(2000): boost::lexical_cast<unsigned>(count_s);
		limit = std::min(limit, size_t(2000));
		limit = std::max(limit, size_t(1));

		StreamGroup sg(req);
		auto& fout = sg.fout;
		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";

#if 1
		fout << boost::format(R"({"func":"common/listuser",
"args":{},
"ret":{"success":true, "message":"",
"total":%1%,
"value":[)") % sctx.user_info.size();
#endif

		std::lock_guard<std::mutex> guard(sctx.mutex);
		auto itr = sctx.user_info.begin();
		std::advance(itr, std::min(sctx.user_info.size(), from));
		bool first = true;
		for(; itr != sctx.user_info.end() && 0 < limit; ++itr, --limit){
			if (first)
				first = false;
			else
				fout << ",";

			fout << "{";


			fout << "\"id\":";
			fout << escape_string(itr->second.userid);
			fout << ",";
			fout << "\"account\":";
			fout << escape_string(itr->first);
			fout << ",";
			fout << "\"role\":";
			fout << escape_string(itr->second.role);
			fout << ",";
			fout << "\"name\":";
			fout << escape_string(itr->second.displayName);

			fout << "}";

		}
		fout << "]}}";
		if (!callback.empty()) sg.fout << ")";
	}
}

static CommandAddHelper k_registerHandler("GET", webcmd::K_this_command, &webcmd::list_user, {"admin"});
}


